package com.guangwei.learnchinesecharacter

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*
import android.content.Context
import java.io.FileNotFoundException


class MainActivity : AppCompatActivity() {
    private var testTimer: Timer? = null
    private var count: Int = 0
    private var totalWords: Int = 0
    private var testedWords: Int = 0
    private var testDuration: Int = 0
    private var status: String = "生词总数：$totalWords\n已默生词：$testedWords\n已用时间：${testDuration}s\n"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        handleButtons()
    }

    override fun onStart() {
        super.onStart()
        initData()
    }

    override fun onPause() {
        super.onPause()
        val delay = et_delay.text.toString().toInt()
        val pref = getSharedPreferences("setting", Context.MODE_PRIVATE)
        val editor = pref.edit()
        editor.putInt("test_delay", delay)
        editor.commit()
    }

    override fun onDestroy() {
        super.onDestroy()
        TTSUtils.getInstance(this).destroy()
    }

    private fun initData(){
        // 程序在第一次播放的时候显示“stop failed: not bound to TTS engine”
        // 在onCreate()方法中先播音一次，来规避上面的问题。
        TTSUtils.getInstance(this).play("")

        // load delay time from preferences
        val pref = getSharedPreferences("setting", Context.MODE_PRIVATE)
        val delay = pref.getInt("test_delay", R.string.default_test_delay)
        et_delay.setText(delay.toString())


        totalWords = getFileLines("data.txt")
        status = "生词总数：$totalWords\n已默生词：$testedWords\n已用时间：${testDuration}s\n"
        tv_status.text = status
    }


    private fun handleButtons() {

        btn_add_words.setOnClickListener {
            val intent = Intent(this, WordsListMaintain::class.java)
            startActivity(intent)
        }

        btn_start_test.setOnClickListener {
            btn_start_test.isEnabled = false
            testedWords = 0
            testDuration = 0
            count = 0

            val myContext = this
            testTimer = Timer()
            if (et_delay.text.toString()=="") {
                et_delay.setText(R.string.default_test_delay)
            }
            val delay = et_delay.text.toString().toInt()

            run {
                try {
                    var fileInputStream = openFileInput("data.txt")
                    val bufferedReader = BufferedReader(InputStreamReader(fileInputStream))
                    var line: String
                    testTimer?.schedule(object : TimerTask() {
                        override fun run() {
                            runOnUiThread(Runnable {
                                count++
                                testDuration++
                                status = "生词总数：$totalWords\n已默生词：$testedWords\n已用时间：${testDuration}s\n"
                                tv_status.text = status
                                if ((count%delay == 0) or (count==1)) {
                                    line = bufferedReader.readLine()?:""
                                    if (line != ""){
                                        TTSUtils.getInstance(myContext).play(line)
                                        testedWords++
                                    }
                                    else {
                                        println("Stop the thread")
                                        testTimer?.cancel()
                                        btn_start_test.isEnabled = true
                                        TTSUtils.getInstance(myContext).play("默写结束")
                                    }
                                }
                            })
                        }
                    }, 0, 1000)
                } catch (throwable: Throwable) {
                    // 捕获到异常的处理
                    btn_start_test.isEnabled = true
                }
            }
        }
    }

    private fun getFileLines(fileName: String): Int {
        var lines = 0

        try {
            var fileInputStream = openFileInput("data.txt")
            val bufferedReader = BufferedReader(InputStreamReader(fileInputStream))
            while (true) {
                bufferedReader.readLine()?:break
                lines++
            }
        } catch (e: FileNotFoundException) {
            println("not file $fileName")
            e.printStackTrace()
        }

        return lines
    }
}
